import javax.swing.plaf.basic.BasicScrollPaneUI;
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.HashMap;

public class Main {
    public static void main(String args[]) {
        Scanner cin = new Scanner(System.in);
        // 读取输入，直到没有整型数据可读
        while (cin.hasNext()) {
            int M;
            // 读取N 和 M
            cin.nextInt();
            M = cin.nextInt();
//            System.out.println(String.format("%d %d", N, M));
            // 读取接下来M行
            HashMap<Integer, Integer> fatherMap = new HashMap<>();
            HashMap<Integer, Integer> sizeMap = new HashMap<>();

            for (int i = 0; i < M; i++) {
                // 读取每行的a b c
                int a = cin.nextInt(),
                        b = cin.nextInt(),
                        c = cin.nextInt();
                initialize(a, fatherMap, sizeMap);
                initialize(b, fatherMap, sizeMap);
                if (c == 1) {
                    int headA = findHead(a, fatherMap);
                    int headB = findHead(b, fatherMap);
                    if (headA < headB)
                        union(headA, headB, fatherMap, sizeMap);
                    else if (headA > headB)
                        union(headB, headA, fatherMap, sizeMap);
                }
//                System.out.println(String.format("%d %d %d", a, b, c));
            }
            if (sizeMap.get(1) == null)
                System.out.println(0);
            else
                System.out.println(sizeMap.get(1) - 1);
        }
    }

    public static int findHead(int element, HashMap<Integer, Integer> fatherMap) {
        while (fatherMap.get(element) != element) {
            element = fatherMap.get(element);
        }
        return element;
    }

    public static void union(int element, int element2, HashMap<Integer, Integer> fatherMap, HashMap<Integer, Integer> sizeMap) {
        fatherMap.put(element2, element);
        sizeMap.put(element, sizeMap.get(element) + sizeMap.get(element2));
    }

    public static void initialize(int element, HashMap<Integer, Integer> fatherMap, HashMap<Integer, Integer> sizeMap) {
        fatherMap.putIfAbsent(element, element);
        sizeMap.putIfAbsent(element, 1);
    }
}





